package com.newegg.whois.util;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class ExecutorQueue implements AutoCloseable{
	
	final ExecutorService execute;
	final Condition full;
    final ReentrantLock lock;
    final int max;
    final AtomicInteger counter = new AtomicInteger(0);
	
	public ExecutorQueue(int max) {
		this.execute = Executors.newFixedThreadPool(max);
		this.max = max;
		this.lock = new ReentrantLock(false);
		this.full =  lock.newCondition();
	}
	
	public void submit(Runnable runnable) {
        lock.lock();
        try {
            while (counter.get() >= this.max){
            	try {
					full.await();
				} catch (InterruptedException e) {
					try { Thread.sleep(100); } catch (InterruptedException e1) { e1.printStackTrace(); }
				}
            }
            counter.incrementAndGet();
            this.execute.execute(new Runnable() {
				@Override
				public void run() {
					runnable.run();
					lock.lock();
					try {
						counter.decrementAndGet();
						full.signal();
					} finally {
						lock.unlock();
					}
				}
			});
        } finally {
            lock.unlock();
        }
	}
	
	public void close() {
		this.execute.shutdown();
	}
}
